<template>
  <div class="machine-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="queryParams" class="form-inline">
        <el-form-item label="售货机名称">
          <el-input v-model="queryParams.name" placeholder="请输入售货机名称" clearable />
        </el-form-item>
        <el-form-item label="所属点位">
          <el-select v-model="queryParams.pointId" placeholder="请选择点位" clearable>
            <el-option
              v-for="point in pointList"
              :key="point.id"
              :label="point.name"
              :value="point.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 售货机列表 -->
    <el-table
      v-loading="loading"
      :data="machineList"
      border
      style="width: 100%"
    >
      <el-table-column prop="name" label="售货机名称" />
      <el-table-column prop="pointName" label="所属点位" />
      <el-table-column prop="areaName" label="所属区域" />
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">{{ getStatusLabel(row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button type="success" link @click="handleStatus(row, 'NORMAL')" v-if="row.status !== 'NORMAL'">
            启用
          </el-button>
          <el-button type="warning" link @click="handleStatus(row, 'MAINTENANCE')" v-if="row.status === 'NORMAL'">
            维护
          </el-button>
          <el-button type="info" link @click="handleStatus(row, 'OFFLINE')" v-if="row.status === 'NORMAL'">
            停用
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        :current-page="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 售货机表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      append-to-body
    >
      <el-form
        ref="machineFormRef"
        :model="machineForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="machineForm.name" placeholder="请输入售货机名称" />
        </el-form-item>
        <el-form-item label="所属点位" prop="pointId">
          <el-select v-model="machineForm.pointId" placeholder="请选择点位">
            <el-option
              v-for="point in pointList"
              :key="point.id"
              :label="point.name"
              :value="point.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="machineForm.status" placeholder="请选择状态">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getMachineList, addMachine, updateMachine, deleteMachine, updateMachineStatus } from '@/api/machine'
import { getPointList } from '@/api/point'

// 状态选项
const statusOptions = [
  { label: '正常', value: 'NORMAL' },
  { label: '维护中', value: 'MAINTENANCE' },
  { label: '已停用', value: 'OFFLINE' }
]

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: '',
  pointId: undefined,
  status: undefined
})

// 列表数据
const loading = ref(false)
const machineList = ref([])
const total = ref(0)
const pointList = ref([])

// 获取售货机列表
const getList = async () => {
  try {
    loading.value = true
    const { data } = await getMachineList(queryParams)
    machineList.value = data.list
    total.value = data.total
  } catch (error) {
    console.error('获取售货机列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取点位列表
const getPoints = async () => {
  try {
    const { data } = await getPointList()
    pointList.value = data
  } catch (error) {
    console.error('获取点位列表失败:', error)
  }
}

// 查询按钮点击
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮点击
const resetQuery = () => {
  queryParams.name = ''
  queryParams.pointId = undefined
  queryParams.status = undefined
  handleQuery()
}

// 分页相关方法
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getList()
}

const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getList()
}

// 表单相关
const dialogVisible = ref(false)
const dialogType = ref('') // add 或 edit
const dialogTitle = ref('')
const machineFormRef = ref()
const machineForm = reactive({
  id: undefined,
  name: '',
  pointId: undefined,
  status: 'NORMAL'
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入售货机名称', trigger: 'blur' }
  ],
  pointId: [
    { required: true, message: '请选择所属点位', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 新增按钮点击
const handleAdd = () => {
  dialogType.value = 'add'
  dialogTitle.value = '新增售货机'
  dialogVisible.value = true
  machineForm.id = undefined
  machineForm.name = ''
  machineForm.pointId = undefined
  machineForm.status = 'NORMAL'
}

// 编辑按钮点击
const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogTitle.value = '编辑售货机'
  dialogVisible.value = true
  machineForm.id = row.id
  machineForm.name = row.name
  machineForm.pointId = row.pointId
  machineForm.status = row.status
}

// 提交表单
const submitForm = async () => {
  if (!machineFormRef.value) return
  
  await machineFormRef.value.validate()
  
  try {
    if (dialogType.value === 'add') {
      await addMachine(machineForm)
      ElMessage.success('新增成功')
    } else {
      await updateMachine(machineForm)
      ElMessage.success('修改成功')
    }
    dialogVisible.value = false
    getList()
  } catch (error) {
    console.error('保存售货机失败:', error)
  }
}

// 更新状态
const handleStatus = (row, status) => {
  const statusMap = {
    'NORMAL': '启用',
    'MAINTENANCE': '维护',
    'OFFLINE': '停用'
  }
  
  ElMessageBox.confirm(
    `确认${statusMap[status]}售货机"${row.name}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await updateMachineStatus(row.id, status)
      ElMessage.success(`${statusMap[status]}成功`)
      getList()
    } catch (error) {
      console.error('更新状态失败:', error)
    }
  })
}

// 删除按钮点击
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确认删除售货机"${row.name}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteMachine(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除售货机失败:', error)
    }
  })
}

// 获取状态标签类型
const getStatusType = (status) => {
  const map = {
    'NORMAL': 'success',
    'MAINTENANCE': 'warning',
    'OFFLINE': 'info'
  }
  return map[status] || ''
}

// 获取状态标签文本
const getStatusLabel = (status) => {
  const option = statusOptions.find(item => item.value === status)
  return option ? option.label : status
}

onMounted(() => {
  getList()
  getPoints()
})
</script>

<style scoped>
.machine-container {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
}

.form-inline {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-wrap: wrap;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  text-align: right;
}
</style> 